Learn MATLAB in 10 Minutes
MATLAB (Matrix Laboratory) is a high-level programming language and environment designed for numerical computing, algorithm development, and data visualization. Originally developed in the late 1970s, MATLAB has become an essential tool in engineering, science, and mathematics.
This tutorial covers MATLAB fundamentals and helps you get started with this powerful computing environment.
1. Your First MATLAB Program
Create a script file named hello.m or type commands directly in the MATLAB command window.
disp('Hello, World!')
Or using the fprintf function:
fprintf('Hello, World!\n')
The output will be:
Hello, World!
The disp() function displays the content directly, while fprintf() provides more formatting control, similar to C’s printf.
2. Basic Syntax
MATLAB has its own syntax rules that differ from most general-purpose programming languages. Understanding these basics is essential for writing clean, maintainable code.
2.1 Comments
Single-line comments start with the percent sign %:
% This is a comment
x = 10; % This assigns 10 to x
Multi-line comments use %{ and %}:
%{
This is a multi-line comment.
It can span multiple lines.
%}
2.2 Semicolons
The semicolon ; suppresses output display. Without it, MATLAB displays the result:
x = 5 % Displays: x = 5
y = 10; % No output, but y is assigned
2.3 Case Sensitivity
MATLAB is case-sensitive. A and a are different variables:
A = 5;
a = 10;
disp(A) % Output: 5
disp(a) % Output: 10
2.4 Variable Naming
Variable names must start with a letter, followed by letters, numbers, or underscores:
valid_name = 1;
another_valid_name_123 = 2;
% 123invalid = 3; % Error: cannot start with number
2.5 Basic Operations
MATLAB excels at matrix operations. Creating a matrix is straightforward:
A = [1 2 3; 4 5 6; 7 8 9] % 3x3 matrix
Output:
A =
1 2 3
4 5 6
7 8 9
3. Variables and Data Types
MATLAB uses dynamic typing. Variables are created when assigned and their type is determined by the assigned value.
3.1 Numeric Types
MATLAB stores all numbers as double-precision floating point by default:
% Integer
int_num = 42;
% Float
float_num = 3.14159;
% Scientific notation
sci_num = 2.5e-3; % 0.0025
3.2 Strings
String variables use single quotes:
str = 'Hello, MATLAB';
str2 = "Hello, MATLAB"; % String array (R2016b+)
String concatenation:
str1 = 'Hello';
str2 = 'World';
combined = [str1 ', ' str2]; % 'Hello, World'
3.3 Logical (Boolean)
Logical values are true or false:
flag = true;
result = false;
% Logical operations
a = true;
b = false;
and_result = a && b; % false
or_result = a || b; % true
not_result = ~a; % false
3.4 Character Arrays vs Strings
MATLAB has both character arrays and string objects:
% Character array (older style)
char_arr = 'Hello';
% String object (modern style, R2016b+)
str_obj = "Hello";
% String objects are easier to work with
name = "Alice";
greeting = "Hello, " + name; % Works naturally
4. Data Structures
MATLAB provides several data structures for different use cases.
4.1 Vectors
A vector is a one-dimensional array:
% Row vector
row_vec = [1 2 3 4 5];
% Column vector
col_vec = [1; 2; 3; 4; 5];
% Using colon operator
range_vec = 1:5; % [1 2 3 4 5]
step_vec = 0:2:10; % [0 2 4 6 8 10]
% linspace for evenly spaced values
lin_vec = linspace(0, 10, 5); % [0 2.5 5 7.5 10]
4.2 Matrices
Matrices are the foundation of MATLAB:
% Direct matrix creation
A = [1 2 3; 4 5 6; 7 8 9];
% Accessing elements
element = A(2, 3); % Returns 6 (row 2, column 3)
% Matrix operations
B = A'; % Transpose
C = A * B; % Matrix multiplication
D = A .* B; % Element-wise multiplication
4.3 Cell Arrays
Cell arrays can hold different types of data:
% Create a cell array
cell_arr = {1, 'hello', [1 2 3], true};
% Access cell contents using curly braces
data = cell_arr{2}; % Returns 'hello'
% Access cell using parentheses
sub_cell = cell_arr(1:2); % Returns {1, 'hello'}
4.4 Structures
Structures are like dictionaries with named fields:
% Create a structure
student.name = 'John';
student.age = 20;
student.major = 'Engineering';
% Access fields
disp(student.name); % Output: John
% Array of structures
students(1).name = 'Alice';
students(1).age = 21;
students(2).name = 'Bob';
students(2).age = 22;
4.5 Tables
Tables are suitable for tabular data:
% Create a table
Age = [25; 30; 35];
Name = {'Alice'; 'Bob'; 'Charlie'};
Salary = [50000; 60000; 70000];
T = table(Name, Age, Salary);
% Access data
disp(T.Age);
disp(T.Name{1});
5. Operators
MATLAB provides various operators for arithmetic, comparison, and logical operations.
5.1 Arithmetic Operators
a = 10;
b = 3;
sum = a + b; % 13
diff = a - b; % 7
prod = a * b; % 30
quot = a / b; % 3.3333
int_div = floor(a/b); % 3
mod = mod(a, b); % 1 (remainder)
pow = a ^ b; % 1000
5.2 Element-wise Operators
Element-wise operators work on corresponding elements:
A = [1 2 3];
B = [4 5 6];
C = A .* B; % Element-wise: [4 10 18]
D = A.^2; % Element-wise square: [1 4 9]
5.3 Comparison Operators
x = 5;
y = 10;
eq = (x == y); % false
neq = (x ~= y); % true
gt = (x > y); % false
lt = (x < y); % true
ge = (x >= y); % false
le = (x <= y); % true
5.4 Logical Operators
a = true;
b = false;
and_op = a & b; % false (element-wise AND)
or_op = a | b; % true (element-wise OR)
not_op = ~a; % false
and_short = a && b; % false (short-circuit AND)
or_short = a || b; % true (short-circuit OR)
6. Control Flow
MATLAB provides standard control flow structures, but with different syntax from languages like Python.
6.1 if-elseif-else
score = 85;
if score >= 90
grade = 'A';
elseif score >= 80
grade = 'B';
elseif score >= 70
grade = 'C';
else
grade = 'F';
end
disp(grade) % Output: B
6.2 switch
The switch statement compares a single expression against multiple cases:
day = 'Monday';
switch day
case {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'}
disp('Weekday');
case {'Saturday', 'Sunday'}
disp('Weekend');
otherwise
disp('Invalid day');
end
6.3 for Loops
The for loop iterates over a range or array:
% Iterating over a range
for i = 1:5
disp(i);
end
% Iterating over an array
fruits = {'apple', 'banana', 'orange'};
for fruit = fruits
disp(fruit{1});
end
% Nested loops for matrix operations
A = [1 2; 3 4];
B = zeros(2, 2);
for i = 1:2
for j = 1:2
B(i, j) = A(i, j) * 2;
end
end
6.4 while Loops
count = 0;
while count < 5
disp(count);
count = count + 1;
end
6.5 Loop Control
The break statement exits the loop, and continue skips to the next iteration:
% Using break
for i = 1:10
if i == 5
break;
end
disp(i);
end
% Output: 1 2 3 4
% Using continue
for i = 1:5
if mod(i, 2) == 0
continue; % Skip even numbers
end
disp(i);
end
% Output: 1 3 5
7. Input and Output
7.1 User Input
Use the input() function to get user input:
% Get numeric input
num = input('Enter a number: ');
% Get string input
name = input('Enter your name: ', 's');
% Get expression input (evaluates the input)
expr = input('Enter an expression: ');
7.2 Displaying Output
Several functions display output:
% disp - simple display
disp('Hello');
disp([1 2 3]);
% fprintf - formatted output
name = 'Alice';
age = 25;
fprintf('Name: %s, Age: %d\n', name, age);
% sprintf - create formatted string
str = sprintf('Value: %.2f', 3.14159);
disp(str);
7.3 Format Specifiers
Common format specifiers in MATLAB:
% %s - string
% %d - integer
% %f - floating point
% %.2f - floating point with 2 decimal places
% %e - scientific notation
fprintf('%d %.2f %e\n', 42, 3.14159, 1000)
% Output: 42 3.14 1.000000e+03
8. Functions
Functions in MATLAB are typically defined in separate files, but anonymous functions provide inline function creation.
8.1 Anonymous Functions
Anonymous functions create simple functions without separate files:
% Single input
square = @(x) x^2;
disp(square(5)); % Output: 25
% Multiple inputs
add = @(x, y) x + y;
disp(add(3, 4)); % Output: 7
% Multiple expressions
hypot = @(x, y) sqrt(x^2 + y^2);
disp(hypot(3, 4)); % Output: 5
8.2 Function Files
Create a file named myfunc.m:
function y = myfunc(x)
y = x^2 + 1;
end
Call the function:
result = myfunc(5); % Output: 26
8.3 Functions with Multiple Outputs
function [sum, prod] = calc(x, y)
sum = x + y;
prod = x * y;
end
Call with multiple outputs:
[s, p] = calc(3, 4);
disp(s); % 7
disp(p); % 12
8.4 Variable Arguments
Use varargin and varargout for variable arguments:
function result = sum_all(varargin)
result = 0;
for i = 1:length(varargin)
result = result + varargin{i};
end
end
% Call with any number of arguments
total = sum_all(1, 2, 3, 4, 5); % Output: 15
9. Script Files
Scripts are .m files that contain a sequence of MATLAB commands. They operate on data in the workspace:
% save as myscript.m
% Calculate statistics for a dataset
data = [1 2 3 4 5 6 7 8 9 10];
mean_val = mean(data);
std_val = std(data);
max_val = max(data);
min_val = min(data);
fprintf('Mean: %.2f\n', mean_val);
fprintf('Std: %.2f\n', std_val);
fprintf('Max: %d\n', max_val);
fprintf('Min: %d\n', min_val);
10. Error Handling
Use try-catch for error handling:
try
result = risky_operation();
catch ME
fprintf('Error: %s\n', ME.message);
% Handle the error
result = 0;
end
Using error() to raise errors:
function result = divide(a, b)
if b == 0
error('Division by zero is not allowed');
end
result = a / b;
end
11. File Operations
11.1 Saving and Loading Data
% Save variables to file
x = [1 2 3];
y = 'hello';
save('data.mat', 'x', 'y');
% Load variables from file
load('data.mat');
% Save to text file
writematrix(x, 'data.txt');
% Read from text file
data = readmatrix('data.txt');
11.2 Text File Operations
% Write to text file
fid = fopen('output.txt', 'w');
fprintf(fid, 'Line 1\n');
fprintf(fid, 'Line 2\n');
fclose(fid);
% Read from text file
fid = fopen('output.txt', 'r');
while ~feof(fid)
line = fgetl(fid);
if ischar(line)
disp(line);
end
end
fclose(fid);
Using textscan for structured reading:
fid = fopen('data.txt', 'r');
format = '%s %d %f';
C = textscan(fid, format);
fclose(fid);
name = C{1};
age = C{2};
score = C{3};
12. Plotting
MATLAB’s plotting capabilities are one of its strongest features.
12.1 Basic 2D Plotting
x = 0:0.1:2*pi;
y = sin(x);
plot(x, y);
xlabel('x');
ylabel('sin(x)');
title('Sine Wave');
grid on;
12.2 Multiple Plots
x = 0:0.1:2*pi;
% Subplots
subplot(2, 1, 1);
plot(x, sin(x));
title('Sine');
subplot(2, 1, 2);
plot(x, cos(x));
title('Cosine');
12.3 Plot Customization
x = 0:0.1:10;
y1 = x;
y2 = x.^2;
plot(x, y1, 'b-', 'LineWidth', 2); % Blue solid line
hold on;
plot(x, y2, 'r--', 'LineWidth', 2); % Red dashed line
hold off;
xlabel('X');
ylabel('Y');
legend('Linear', 'Quadratic');
title('Linear vs Quadratic');
grid on;
12.4 Other Plot Types
% Bar chart
bar([1 2 3 4], [10 20 15 25]);
% Histogram
data = randn(1000, 1);
histogram(data, 30);
% Scatter plot
x = rand(100, 1);
y = 2*x + randn(100, 1)*0.1;
scatter(x, y);
